<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
        "http://www.w3.org/TR/html4/loose.dtd">
<!--
    Copyright 2010 Aravindan Ramkumar
    
    Licensed under the Apache License, Version 2.0 (the "License");
    you may not use this file except in compliance with the License. You may obtain a copy of the License at

        http://www.apache.org/licenses/LICENSE-2.0

    Unless required by applicable law or agreed to in writing, software
    distributed under the License is distributed on an "AS IS" BASIS,
    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    See the License for the specific language governing permissions and limitations under the License.
-->
<html>
<head>
    <title>Site Search</title>
    <link rel="stylesheet" type="text/css" href="lib/fonts-min.css"/>
    <link rel="stylesheet" type="text/css" href="lib/paginator.css"/>
    <link href="lib/site-search.css" rel="stylesheet" type="text/css"/>
    <script type="text/javascript" src="lib/yahoo-dom-event.js"></script>
    <script type="text/javascript" src="lib/element-min.js"></script>
    <script type="text/javascript" src="lib/paginator-min.js"></script>    
    <script type="text/javascript">
        var HTTP = "http://";
        var HTTPS = "https://";
        var ROWS_PER_PAGE = 10;
        var MAX_LENGTH = 1024;        

        // Set up the application under the YAHOO.sitesearch namespace
        var Ss = YAHOO.namespace('sitesearch');

        var D = YAHOO.util.Dom;

        Ss.isValid = function (url) {
            return url.indexOf(HTTP) != -1 || url.indexOf(HTTPS) != -1;
        };

        /**
         * Callback which receives the selected text. Calls search().
         * @param text The text to search for.
         */
        Ss.onSelection = function(text) {
            D.setAttribute('q','value',text.substring(0,MAX_LENGTH));
            search();
        };                 

        chrome.tabs.getSelected(null, function(tab) {
            Ss.selectedTabUrl = tab.url;
            Ss.selectedTabId = tab.id;
            if (Ss.isValid(tab.url)) {
                // look for selected text
                chrome.extension.getBackgroundPage().getSelection(tab.id, Ss.onSelection);
                var noProtocol = tab.url.replace(HTTP, "").replace(HTTPS, "");
                Ss.domainName = noProtocol.substring(0, noProtocol.indexOf('/'));
                D.get('domainName').innerHTML = Ss.domainName;
                D.get('q').focus();
            } else {
                D.get('results').innerHTML = '<strong>Site Not Searchable</strong>';
            }
        });

        Ss.handlePagination = function (state) {                        
            chrome.extension.getBackgroundPage().search({
                textToSearch : Ss.textToSearch,
                domainName : Ss.domainName,
                start : state.recordOffset,
                success : Ss.onSuccess,
                failure : Ss.onFailure
            });

            // Update the Paginator's state, confirming change
            Ss.paginator.setState(state);
        };

        Ss.onFailure = function(response) {
            D.get('results').innerHTML = '<br><strong>' + response.error + '</strong>';
            Ss.paginator = null;
            D.get('pageNum').innerHTML = '';
            D.get('info').style.display = 'none';
        };

        Ss.onSuccess = function(response) {
            if (!response.total || response.total == 0) {
                D.get('results').innerHTML = '<br><strong>Search produced no results</strong>';
                Ss.paginator = null;
                D.get('pageNum').innerHTML = '';
                D.get('info').style.display = 'none';
                return;
            }

            if (!Ss.paginator) {
                // Create the Paginator widget and subscribe to its changeRequest event
                Ss.paginator = new YAHOO.widget.Paginator({
                    rowsPerPage : ROWS_PER_PAGE,
                    containers : 'pageNum',
                    totalRecords : response.total,
                    template : '{PreviousPageLink}{PageLinks}{NextPageLink}'
                });

                Ss.paginator.subscribe('changeRequest', Ss.handlePagination);

                // Render the Paginator into the configured container(s)
                Ss.paginator.render();
            }

            Ss.paginator.set("totalRecords", response.total);

            // show info
            D.get("info").style.display = 'block';

            // update indexes
            D.get("startIndex").innerHTML = response.start + 1;
            D.get("endIndex").innerHTML = response.start + (response.total < ROWS_PER_PAGE ? response.total : ROWS_PER_PAGE);
            D.get("total").innerHTML = response.total;

            Ss.createResultset(response);
        };

        Ss.createResultset = function(data) {
            var str = '<ul>';
            var regEx = new RegExp(Ss.textToSearch, "gi");
            for (var index = 0; index < data.results.length; index++) {
                var result = data.results[index];
                str += '<li><h3><a href="javascript:openTab(\'' + result.url + '\')">' + result.title.replace(regEx, '<em>$&</em>') + '</a></h3>';
                str += '<div>';
                str += result.description.replace(regEx, '<em>$&</em>');
                str += '<br><cite>';
                str += result.displayUrl;
                str += "</cite></div></li>"
            }
            str += '</ul>';

            D.get('results').innerHTML = str;
        };

        function search() {
            Ss.textToSearch = D.get('q').value;
            if (Ss.textToSearch != null && Ss.textToSearch != "") {
                if (Ss.isValid(Ss.selectedTabUrl)) {
                    if(localStorage['provider'] == 'google') {
                        openTab("http://www.google.com/search?q=site:" + Ss.domainName + " " + Ss.textToSearch);
                        // close the popup
                        window.close();
                    } else {
                        chrome.extension.getBackgroundPage().search({
                            textToSearch : Ss.textToSearch,
                            domainName : Ss.domainName,
                            start : 0,
                            success : Ss.onSuccess,
                            failure : Ss.onFailure
                        });
                    }
                }
            }
        }

        function openTab(hrefUrl) {
            var tab_select = localStorage['tab_select'] || "same_tab";
            if(tab_select == 'same_tab') {
                chrome.tabs.update(Ss.selectedTabId, {url : hrefUrl});
            } else if(tab_select == 'new_tab') {
                chrome.tabs.create({url : hrefUrl})
            }
        }
    </script>
</head>
<body class="yui-skin-sam" style="width: 500px;">
<form action="" onsubmit="search();">
    <input type="text" id="q" size="41" maxlength="1024" />
    <input type="button" onclick="search();" value="Search" id="searchBtn" />
    <br><span id="domainName" style="color: brown;"></span>&nbsp;
</form>
<div id="pageNum"></div>
<div id="info" style="display:none;">Results <span id="startIndex" class="bold"></span> - <span id="endIndex"
                                                                                                 class="bold"></span>
    of about <span id="total" class="bold"></span></div>
<div id="results"></div>
</body>
</html>